package com.demo.common.model;

import java.lang.reflect.ParameterizedType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;

public class BaseModel<T extends Model<T>> extends Model<T>{
	private static Logger logger = Logger.getLogger(BaseModel.class);  
	protected Class<T> clazz;
	//参数化类型反射  
	public BaseModel(){
			ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
			this.clazz = (Class<T>) pt.getActualTypeArguments()[0];
			System.out.println("clazz="+clazz.getName());
	}
	
	public Page<T> paginate(int pageNumber, int pageSize,String WhereSql,Map<String, String[]> params) {
		StringBuilder tmpHql = new StringBuilder(" from "+clazz.getSimpleName() +" o where 1 = 1");
		/*if(params!=null){
            for(String key:params.keySet()){
                	tmpHql.append(" and o.").append(key).append("=:").append(key);
            }
    
        }*/
		return paginate(pageNumber, pageSize, "SELECT o", tmpHql.toString());
	}
	
	public List<T> findObjectByConditionWithNoPage(String whereHql,Object[] values) {
		return findObjectByConditionWithNoPage(whereHql,values,null);
	}
	/**
	 * and like .. and  o.ksjdk = ? and 
	 * @param whereHql
	 * @param values
	 * @param orderby
	 * @return
	 */
	public List<T> findObjectByConditionWithNoPage(String whereHql,
			Object[] values, LinkedHashMap<String, String> orderby) {
		String tmpHql = getTmpSql(whereHql, orderby);
		System.out.println("----->tmpHql:"+tmpHql);
		return find(tmpHql, values);
	}
	
	/*
	 * 得到处理的查询语句
	 */
	private String getTmpSql(String whereHql,
			LinkedHashMap<String, String> orderby) {
		StringBuilder tmpHql = new StringBuilder("select o from "+clazz.getSimpleName() +" o where 1 = 1");
		//处理排序
		String orderbystr = buildOrdeyBy(orderby);
		tmpHql.append(whereHql).append(orderbystr);
		return tmpHql.toString();
	}

	
	/**
	 * @param orderby
	 */
	public String buildOrdeyBy(LinkedHashMap<String, String> orderby) {
		StringBuffer buf = new StringBuffer("");
		if(orderby!=null&&!orderby.isEmpty()){
			buf.append(" order by ");
			for(Map.Entry<String, String> em:orderby.entrySet()){
				buf.append(em.getKey()+" "+em.getValue());
			}
			//去掉最后一个 “，”逗号
			buf.deleteCharAt(buf.length()-1);
			System.out.println("buf:"+buf.toString());
		}
		return buf.toString();
	}


}
